package virtualapp

import (
	"encoding/json"
	"net/url"
	"strings"
	"time"

	"gitee.com/tomatomeatman/golang-repository/bricks2/function/httputil"
	"gitee.com/tomatomeatman/golang-repository/bricks2/model/msgentity"
	"gitee.com/tomatomeatman/golang-repository/bricks2/utils/ginutil"
	"github.com/cihub/seelog"
)

type Cloud struct{}

/**
 * 初始化
 */
func init() {
	if !(IsCloudApp()) {
		return
	}

	go ginutil.ControllerRegister("/cloud/monitor", Cloud{}.CloudMonitor, ginutil.POST)
	go ginutil.ControllerRegister("/cloud/monitor", Cloud{}.CloudMonitor, ginutil.GET)
}

/**
 * 注册服务到注册中心
 */
func (Cloud) RegistraCloud() {
	if !(IsCloudApp()) {
		return
	}

	cloudCenterSite := ReadConfigKey("CloudCenter", "Site", "").(string)
	cloudCenterUser := ReadConfigKey("CloudCenter", "User", "").(string)
	cloudCenterPassword := ReadConfigKey("CloudCenter", "Password", "").(string)
	DomainName := ReadConfigKey("System", "DomainName", "").(string)
	DomainPort := ReadConfigKey("System", "DomainPort", "").(string)

	Port := ReadConfigKey("System", "Port", "8080").(string)
	Name := ReadConfigKey("System", "Name", "").(string)

	var builder strings.Builder
	builder.WriteString("{\"sign\":\"")
	builder.WriteString(Name)
	builder.WriteString("Server\",\"serverPort\":\"")
	builder.WriteString(Port)
	builder.WriteString("\",\"serverIp\":\"unknown\",\"domainName\":\"")
	builder.WriteString(DomainName)
	builder.WriteString("\",\"domainPort\":\"")
	builder.WriteString(DomainPort)
	builder.WriteString("\"}")

	var host strings.Builder
	host.WriteString("http://")
	host.WriteString(cloudCenterSite)
	host.WriteString("/add")

	params := map[string]interface{}{
		"user":        cloudCenterUser,
		"key":         cloudCenterPassword,
		"sign":        Name + "Server",
		"registerTxt": url.QueryEscape(builder.String()),
	}

	urlStr := strings.Replace(host.String(), "http://http://", "http://", 1)

	for {
		bl, msg, data := httputil.DoGet(urlStr, params, nil)
		if !bl {
			seelog.Error("注册服务失败,返回内容:", msg)
			time.Sleep(time.Second * 5) //休眠5秒
			continue
		}

		me := msgentity.MsgEntity{}
		err := json.Unmarshal([]byte(data.(string)), &me)
		if err != nil {
			seelog.Error("Json字符串转换异常: %+v\n", err)
			continue
		}

		if !me.Success {
			seelog.Error("注册服务失败,返回内容:", me.Msg)
			time.Sleep(time.Second * 5) //休眠5秒
			continue
		}

		//fmt.Println("注册服务成功")
		seelog.Info("注册服务成功")
		return
	}
}

// #region @Api {title=中心监听接口}
// @return {type=json explainType=MsgEntity<string> explain=返回响应}
// @RequestMapping {name=CloudMonitor type=GET,POST value=/cloud/monitor}
// #endregion
func (Cloud) CloudMonitor(ctx ginutil.Context) interface{} {
	return msgentity.Success(time.Now().Format("2006-01-02 15:04:05"), "访问成功")
}
